/**
 * MongoDB 测试路由
 * 用于测试MongoDB集成功能
 */

import { Router } from "express";
import { connectMongoDB, getConnectionStatus, checkConnection } from "../config/mongodb";
import { mongoDBService } from "../services/mongodb-service";

const router = Router();

// 测试数据库连接
router.get("/connection", async (req, res) => {
  try {
    const status = getConnectionStatus();
    const isHealthy = await checkConnection();
    
    res.json({
      success: true,
      status,
      healthy: isHealthy,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '连接测试失败'
    });
  }
});

// 初始化数据库连接
router.post("/init", async (req, res) => {
  try {
    await connectMongoDB();
    
    res.json({
      success: true,
      message: "MongoDB连接初始化成功",
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '初始化失败'
    });
  }
});

// 同步内存用户数据到MongoDB
router.post("/sync-users", async (req, res) => {
  try {
    // 导入用户数据库（需要从auth.ts导入）
    const { userDb } = await import("./auth");
    
    await mongoDBService.syncUsersFromMemory(userDb);
    
    res.json({
      success: true,
      message: `成功同步 ${userDb.size} 个用户到MongoDB`,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '用户同步失败'
    });
  }
});

// 同步人脸数据
router.post("/sync-face", async (req, res) => {
  try {
    const path = await import("path");
    const faceDataPath = path.join(process.cwd(), "face_data.json");
    
    await mongoDBService.syncFaceDataFromFile(faceDataPath);
    
    res.json({
      success: true,
      message: "人脸数据同步成功",
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '人脸数据同步失败'
    });
  }
});

// 获取MongoDB中的用户列表
router.get("/users", async (req, res) => {
  try {
    const users = await mongoDBService.getAllUsers();
    
    res.json({
      success: true,
      data: users,
      count: users.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取用户列表失败'
    });
  }
});

// 测试创建OCR记录
router.post("/test-ocr", async (req, res) => {
  try {
    const testRecord = await mongoDBService.saveOCRRecord({
      userId: 'test_user',
      imageUrl: '/test/image.jpg',
      ocrType: 'general',
      serviceType: 'ppocr',
      recognitionResult: {
        success: true,
        text: '测试OCR识别文本',
        confidence: 0.95
      },
      processingTime: 1500
    });
    
    res.json({
      success: true,
      data: testRecord,
      message: "OCR记录创建成功"
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : 'OCR记录创建失败'
    });
  }
});

// 测试创建医疗告警
router.post("/test-alert", async (req, res) => {
  try {
    const testAlert = await mongoDBService.createMedicalAlert({
      type: 'device',
      title: '测试设备告警',
      location: '测试位置',
      status: 'active',
      priority: 'medium',
      description: '这是一个测试告警',
      assignee: '测试负责人'
    });
    
    res.json({
      success: true,
      data: testAlert,
      message: "医疗告警创建成功"
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '医疗告警创建失败'
    });
  }
});

// 获取医疗告警列表
router.get("/alerts", async (req, res) => {
  try {
    const { status, priority, type, limit } = req.query;
    
    const alerts = await mongoDBService.getMedicalAlerts({
      status: status as string,
      priority: priority as string,
      type: type as string,
      limit: limit ? parseInt(limit as string) : undefined
    });
    
    res.json({
      success: true,
      data: alerts,
      count: alerts.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取告警列表失败'
    });
  }
});

// 获取OCR统计信息
router.get("/ocr-stats", async (req, res) => {
  try {
    const { userId } = req.query;
    const stats = await mongoDBService.getOCRStats(userId as string);
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取OCR统计失败'
    });
  }
});

// 获取告警统计信息
router.get("/alert-stats", async (req, res) => {
  try {
    const stats = await mongoDBService.getAlertStats();
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取告警统计失败'
    });
  }
});

// 记录测试日志
router.post("/test-log", async (req, res) => {
  try {
    const testLog = await mongoDBService.logAction({
      userId: 'test_user',
      action: 'test_action',
      module: 'mongodb_test',
      level: 'info',
      message: '这是一条测试日志',
      ipAddress: req.ip,
      userAgent: req.get('User-Agent')
    });
    
    res.json({
      success: true,
      data: testLog,
      message: "测试日志记录成功"
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '日志记录失败'
    });
  }
});

// 清理测试数据
router.delete("/cleanup", async (req, res) => {
  try {
    const { User, OCRRecord, MedicalAlert, SystemLog } = await import("../models/mongodb-schemas");
    
    // 删除测试数据
    await User.deleteMany({ userId: { $regex: /^test_/ } });
    await OCRRecord.deleteMany({ userId: 'test_user' });
    await MedicalAlert.deleteMany({ alertId: { $regex: /^alert_.*test/ } });
    await SystemLog.deleteMany({ userId: 'test_user' });
    
    res.json({
      success: true,
      message: "测试数据清理完成"
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '数据清理失败'
    });
  }
});

export default router;